<template>
	<view class="page-container"
		:style="{ backgroundImage: `url(${musicList?.info.coverImg || playlistData?.coverImgUrl})` }">
		<!-- 背景模糊层 -->
		<view class="bg-blur-layer">
			<image :src="musicList?.info.coverImg || playlistData?.coverImgUrl" class="blur-image" mode="aspectFill">
			</image>
		</view>

		<!-- 内容区域 -->
		<view class="content-wrapper">
			<UAMHeader :title="title" transparent></UAMHeader>

			<view v-if="playlistData">
				<!-- 封面和信息区域 -->
				<view class="cover-info-section">
					<view class="cover-container">
						<image :src="musicList?.info.coverImg || playlistData?.coverImgUrl" class="cover-image"
							mode="aspectFill" lazy-load></image>
						<text class="play-count">
							<text class="iconfont icon-bofang "></text>
							{{ musicList?.info.playCount > 10000000? 
                 formatPlayCount(musicList.info.playCount)+'亿' : 
                 formatPlayCount(musicList.info.playCount)+'万' }}
						</text>
					</view>

					<view class="info-section">
						<text class="title">{{ musicList?.info.name || playlistData?.name }}</text>

						<!-- 用户头像 -->
						<view class="avatar-container">
							<image :src="'/static/avater1.jpg'" class="avatar-image" mode="aspectFill"></image>
							<text>doro想吃origin</text>
						</view>
						<text class="description">{{ musicList?.info.description || playlistData?.description }}</text>
					</view>
				</view>


				<!-- 歌曲列表 -->
				<scroll-view class="track-scroll" scroll-y :scroll-top="scrollTop">
					<view class="action-bar">
						<view class="btn play-all" @click="playAll">
							<text class="iconfont icon-bofang"></text>
							<text>播放全部</text>
							<text
								class="track-count">({{ musicList?.songs.length || playlistData?.tracks.length }})</text>
						</view>
					</view>
					<view class="tracks-container">
						<view v-for="(song, index) in musicList?.songs" :key="song.id" class="track-item"
							@click="playSong(song.originData)">
							<text class="track-number">{{ index + 1 }}</text>
							<view class="track-info">
								<text class="track-name">{{ song.name }}</text>
								<view class="track-meta">
									<text v-if="song.isFee && !song.isPlayable" class="vip-tag">VIP</text>
									<text v-if="song.isSQ" class="sq-tag">SQ</text>
									<text class="artists">
										{{ song.artists.map(artist => artist.name).join(' / ') }}
										{{ song.album?.name ? ' - ' + song.album.name : '' }}
									</text>
								</view>
							</view>
							<text class="iconfont icon-play more-btn"></text>
						</view>
					</view>
				</scroll-view>
			</view>

			<view v-else class="loading">
				<view class="loading-spinner"></view>
				<text>数据加载中...</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		listDetail,
		songDetail
	} from '@/common/api.js';

	export default {
		data() {
			return {
				title: "歌单",
				currentChartId: null,
				playlistData: null,
				musicList: null, // 新增更贴合数据的数组
				scrollHeight: 600,
				scrollTop: 0
			};
		},
		onLoad(options) {
			console.log(options);
			if (options.id) {
				this.currentChartId = options.id;
				this.calcScrollHeight();
				this.fetchListDetail();
			}
		},
		methods: {
			calcScrollHeight() {
				const systemInfo = uni.getSystemInfoSync();
				// 动态计算滚动区域高度，考虑不同设备的屏幕尺寸
				const screenHeight = systemInfo.windowHeight;
				// 减去顶部区域高度（状态栏+标题栏+封面信息区域）的估算值
				const topAreaHeight = 420; // 单位为px
				this.scrollHeight = (screenHeight - topAreaHeight) * 2; // 转换为rpx（大约是px的2倍）
			},

			async fetchListDetail() {
				try {
					const res = await listDetail(this.currentChartId);
					if (res.data?.code === 200) {
						// 获取歌曲详情，以获取privileges信息
						// 增加歌曲获取数量，从50首增加到200首
						const trackIds = res.data.playlist.trackIds.map(item => item.id).slice(0, res.data.playlist
							.tracks.length); // 增加数量限制，但仍保留一定限制避免请求过大
						const songRes = await songDetail(trackIds);

						// 创建privileges的映射，以便快速查找
						const privilegesMap = {};
						if (songRes.data?.privileges) {
							songRes.data.privileges.forEach(privilege => {
								privilegesMap[privilege.id] = privilege;
							});
						}

						// 将privileges信息关联到tracks
						const tracksWithPrivileges = res.data.playlist.tracks.map(track => {
							const privilege = privilegesMap[track.id];
							return {
								...track,
								privilege: privilege // 添加privilege属性
							};
						});

						// 保存原始数据
						this.playlistData = {
							...res.data.playlist,
							tracks: tracksWithPrivileges,
							description: res.data.playlist.description || '暂无描述'
						};

						// 创建更贴合数据的新数组结构
						this.musicList = {
							info: {
								id: res.data.playlist.id,
								name: res.data.playlist.name,
								coverImg: res.data.playlist.coverImgUrl,
								playCount: res.data.playlist.playCount,
								description: res.data.playlist.description || '暂无描述',
								creator: res.data.playlist.creator ? {
									id: res.data.playlist.creator.userId,
									name: res.data.playlist.creator.nickname,
									avatarUrl: res.data.playlist.creator.avatarUrl
								} : null,
								updateTime: res.data.playlist.updateTime,
								trackCount: res.data.playlist.trackCount
							},
							songs: tracksWithPrivileges.map(track => ({
								id: track.id,
								name: track.name,
								artists: track.ar.map(artist => ({
									id: artist.id,
									name: artist.name
								})),
								album: track.al ? {
									id: track.al.id,
									name: track.al.name,
									coverImg: track.al.picUrl
								} : null,
								duration: track.dt, // 歌曲时长（毫秒）
								isFee: track.fee === 1 || track.fee === 8, // 是否付费歌曲
								isPlayable: track.privilege ? track.privilege.pl > 0 : true, // 是否可播放
								isSQ: !!track.sq, // 是否高品质音乐
								originData: track // 保留原始数据以备不时之需
							}))
						};
					}
				} catch (error) {
					console.error('获取榜单详情失败', error);
					uni.showToast({
						title: '数据加载失败',
						icon: 'none'
					});
				}
			},

			playSong(song) {
				// 检查歌曲对象和ID是否存在
				if (!song || !song.id) {
					console.error('歌曲对象或ID不存在', song);
					uni.showToast({
						title: '无法播放该歌曲',
						icon: 'none'
					});
					return;
				}

				// 确保ID是有效的数字
				const songId = Number(song.id);
				if (isNaN(songId) || songId <= 0) {
					console.error('无效的歌曲ID:', song.id);
					uni.showToast({
						title: '无效的歌曲ID',
						icon: 'none'
					});
					return;
				}

				console.log('准备播放歌曲，ID:', songId);
				uni.navigateTo({
					url: `/pages/player/player?id=${songId}`
				});
			},

			playAll() {
				// 检查是否有歌曲
				if (!this.musicList || !this.musicList.songs || this.musicList.songs.length === 0) {
					uni.showToast({
						title: '没有可播放的歌曲',
						icon: 'none'
					});
					return;
				}

				// 获取所有trackIds
				const trackIds = this.playlistData.trackIds.map(item => item.id);

				// 编码所有ID的数组
				const encodedIds = encodeURIComponent(JSON.stringify(trackIds));

				// 跳转播放页面并传递所有ID
				uni.navigateTo({
					url: `/pages/player/player?ids=${encodedIds}&index=0`
				});
			},

			formatPlayCount(count) {
				return (count >= 10000000 ?
					(count / 100000000).toFixed(1) :
					(count / 10000).toFixed(1));
			}
		}
	};
</script>

<style scoped>
	/* 添加全局过渡效果 */
	@keyframes fadeIn {
		from {
			opacity: 0;
		}

		to {
			opacity: 1;
		}
	}

	@keyframes slideUp {
		from {
			transform: translateY(30rpx);
			opacity: 0;
		}

		to {
			transform: translateY(0);
			opacity: 1;
		}
	}

	/* 页面容器 */
	.page-container {
		animation: fadeIn 0.5s ease;
		position: relative;
		width: 100%;
		min-height: 100vh;
		background-size: cover;
		background-position: center;
		background-attachment: fixed;
	}

	/* 背景模糊层 */
	.bg-blur-layer {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 0;
		overflow: hidden;
		background-color: rgba(0, 0, 0, 0.3);
	}

	.blur-image {
		width: 100%;
		height: 100%;
		filter: blur(50px) brightness(0.7);
		transform: scale(1.2);
	}

	/* 内容区域 */
	.content-wrapper {
		animation: fadeIn 0.6s ease;
		position: relative;
		z-index: 1;
		background-color: transparent;
		min-height: 100vh;
	}



	/* 封面和信息区域 */
	.cover-info-section {
		animation: slideUp 0.8s ease;
		display: flex;
		margin-top: 40rpx;
		margin-bottom: 50rpx;
		padding: 0 20rpx;
	}

	/* 用户头像容器 */
	.avatar-container {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-top: 15rpx;
		margin-bottom: 15rpx;
		color: white;
		font-size: 14px;
	}

	.avatar-image {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		border: 2rpx solid rgba(255, 255, 255, 0.6);
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.2);
		margin-right: 15rpx;
	}

	.share-btn {
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 30rpx;
		padding: 6rpx 12rpx;
		text-align: center;
		margin-left: 10rpx;
	}

	.share-btn text {
		color: white;
		font-size: 22rpx;
		white-space: nowrap;
		line-height: 1.2;
	}

	.cover-container {
		width: 260rpx;
		height: 260rpx;
		position: relative;
		flex-shrink: 0;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.4);
		margin-left: 0;
		border: 2rpx solid rgba(255, 255, 255, 0.2);
	}

	.cover-image {
		width: 100%;
		height: 100%;
	}

	.play-count {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		color: white;
		font-size: 20rpx;
		/* 去掉黑色背景 */
		background-color: transparent;
		padding: 4rpx 10rpx;
		border-radius: 20rpx;
	}

	/* 信息区域 */
	.info-section {
		margin-left: 30rpx;
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.title {
		font-size: 38rpx;
		color: white;
		font-weight: bold;
		line-height: 1.4;
		text-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.6);
		margin-bottom: 10rpx;
	}

	.meta-line {
		margin: 15rpx 0;
	}

	.update-frequency {
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.8);
		background-color: rgba(255, 255, 255, 0.2);
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
	}

	.description {
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.8);
		line-height: 1.4;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	/* 操作按钮栏 */
	.action-bar {
		padding: 20rpx 30rpx;
		background-color: rgba(255, 255, 255, 0.95);
		border-radius: 30rpx 30rpx 0 0;
		display: flex;
		align-items: center;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.btn {
		display: flex;
		align-items: center;
		padding: 12rpx 20rpx;
		border-radius: 50rpx;
		font-size: 28rpx;
	}

	.play-all {
		background-color: #ff4d4f;
		color: #fff;
		box-shadow: 0 4rpx 10rpx rgba(255, 77, 79, 0.3);
		transition: all 0.2s ease;
	}

	.play-all:active {
		background-color: #ff3a3c;
		transform: scale(0.98);
	}

	.play-all .iconfont {
		margin-right: 10rpx;
		font-size: 32rpx;
	}

	.track-count {
		margin-left: 8rpx;
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.9);
	}

	/* 歌曲列表 */
	.track-scroll {
		background-color: rgba(255, 255, 255, 0.95);
		box-shadow: 0 -10rpx 20rpx rgba(0, 0, 0, 0.15);
		width: 100%;
		height: calc(100vh - 60rpx);
		border-radius: 30rpx 30rpx 0 0;
		margin-top: 0;
	}

	.track-item {
		display: flex;
		align-items: center;
		padding: 24rpx 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
		background-color: rgba(255, 255, 255, 0.95);
		transition: background-color 0.2s ease;
	}

	.track-item:active {
		background-color: rgba(245, 245, 245, 0.95);
	}

	.track-number {
		width: 60rpx;
		text-align: center;
		color: #999;
		font-size: 28rpx;
		font-weight: 500;
	}

	.track-info {
		flex: 1;
		margin-left: 15rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}

	.track-name {
		font-size: 30rpx;
		color: #333;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		margin-bottom: 8rpx;
		font-weight: 500;
	}

	.track-meta {
		display: flex;
		align-items: center;
		flex-wrap: nowrap;
	}

	.sq-tag {
		font-size: 16rpx;
		color: #ff4d4f;
		background-color: transparent;
		border-radius: 6rpx;
		margin-right: 10rpx;
		font-weight: bold;
		border: 1rpx solid #ff4d4f;
		padding: 0 4rpx;
	}

	.vip-tag {
		font-size: 16rpx;
		color: #ffaa00;
		background-color: transparent;
		border-radius: 6rpx;
		margin-right: 10rpx;
		font-weight: bold;
		border: 1rpx solid #ffaa00;
		padding: 0 4rpx;
	}

	.artists {
		font-size: 24rpx;
		color: #888;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		line-height: 1.2;
	}

	.more-btn {
		color: #ff4d4f;
		font-size: 40rpx;
		padding: 10rpx 20rpx 10rpx 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.loading {
		text-align: center;
		padding: 100rpx 0;
		color: white;
		font-size: 32rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		border: 6rpx solid rgba(255, 255, 255, 0.3);
		border-top-color: #fff;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>